<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  useMessage,
  NAvatar,
  NButton,
  NFlex,
  NForm,
  NFormItem, NImage,
  NInput,
  NInputNumber,
  NPopconfirm,
  NSelect,
  NTreeSelect
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'

import {getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'

defineOptions({ name: '商品类目' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '商品类目',
  initForm: { order: 0 },
  doCreate: api.creategoodsCategory,
  doUpdate: api.updategoodsCategory,
  doDelete: api.deletegoodsCategory,
  refresh: () => $table.value?.handlerefresh(),
})

const deptOption = ref([])
const isDisabled = ref(false)

const attribute_ms_option = ref([])
const attribute_gg_option = ref([])
const base_path = import.meta.env.VITE_BASE

onMounted(() => {
  $table.value?.handleSearch()
  api.getgoodsCategoryTree().then((res) => (deptOption.value = res.data))
  api.getgoodsAttributeOption({type:1}).then((res) => (attribute_ms_option.value = res.data))
  api.getgoodsAttributeOption({type:2}).then((res) => (attribute_gg_option.value = res.data))
})

const deptRules = {
  name: [
    {
      required: true,
      message: '请输入分类名称',
      trigger: ['input', 'blur', 'change'],
    },
  ],
}

async function addDepts() {
  isDisabled.value = false
  handleAdd()
}

const data = reactive({
    uploadAction: base_path + 'api/goods/category/file',
    token: getToken(),
});

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 120,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '类目名称',
    key: 'name',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
        title: '封面',
        key: 'cover',
        width: '100',
        align: 'center',
        ellipsis: { tooltip: true },
        render(row) {
            let img_src = row.cover
            return h(NFlex, {},
                [h(NAvatar, {
                    src: img_src,
                    size: "small",
                })]
            )

        },
    },
    {
        title: '横幅',
        key: 'banner',
        width: '100',
        align: 'center',
        ellipsis: { tooltip: true },
        render(row) {
            let img_src = row.banner
            return h(NFlex, {},
                [h(NAvatar, {
                    src: img_src,
                    size: "small",
                })]
            )

        },
    },
    {
    title: '排序',
    key: 'order',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '备注',
    key: 'desc',
    align: 'center',
    width: 'auto',
    ellipsis: { tooltip: true },
  },
  {
    title: '操作',
    key: 'actions',
    width: 'auto',
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                console.log('row', row.parent_id)
                if (row.parent_id === 0) {
                  isDisabled.value = true
                } else {
                  isDisabled.value = false
                }
                handleEdit(row)
              },
            },
            {
              default: () => '编辑',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          [[vPermission, 'post/api/content/category/update']]
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ data_id: row.id }, false),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '删除',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                [[vPermission, 'delete/api/content/category/delete']]
              ),
            default: () => h('div', {}, '确定删除该分类吗?'),
          }
        ),
      ]
    },
  },
]

//封面图
const message = useMessage();
const customRequestMethod = (options) => {
    console.log(options, 'options');

    const { file } = options.file;
    const formData = new FormData();
    formData.append('file', file);
    fetch(data.uploadAction, {
        method: 'POST',
        headers: options.headers,
        body: formData,
    })
        .then((response) => response.json())
        .then((data) => {
            console.log(data, 'datatat');
            if (data.code == 200) {
                modalForm.value.cover = data.data.url
                message.success('封面图上传成功');
                options.onProgress(data);
            } else {
                message.error(data.msg);
            }
        })
}

const customRequestMethod2 = (options) => {
    console.log(options, 'options');

    const { file } = options.file;
    const formData = new FormData();
    formData.append('file', file);
    fetch(data.uploadAction, {
        method: 'POST',
        headers: options.headers,
        body: formData,
    })
        .then((response) => response.json())
        .then((data) => {
            console.log(data, 'datatat');
            if (data.code == 200) {
                modalForm.value.banner = data.data.url
                message.success('封面图上传成功');
                options.onProgress(data);
            } else {
                message.error(data.msg);
            }
        })
}
</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="商品类目列表">
    <template #action>
      <div>
        <NButton
          v-permission="'post/api/content/category/create'"
          class="float-right mr-15"
          type="primary"
          @click="addDepts"
        >
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建类目
        </NButton>
      </div>
    </template>
    <!-- 表格 -->
    <CrudTable
      ref="$table"
      v-model:query-items="queryItems"
      :columns="columns"
      :get-data="api.getgoodsCategory"
    >
    </CrudTable>

    <!-- 新增/编辑 弹窗 -->
    <CrudModal
      v-model:visible="modalVisible"
      :title="modalTitle"
      :loading="modalLoading"
      @save="handleSave"
    >
      <NForm
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="modalForm"
        :rules="deptRules"
      >
        <NFormItem label="父级分类" path="parent_id">
          <NTreeSelect
            v-model:value="modalForm.parent_id"
            :options="deptOption"
            key-field="id"
            label-field="name"
            placeholder="请选择父级商品分类"
            clearable
            default-expand-all

          ></NTreeSelect>
        </NFormItem>
        <NFormItem label="分类名称" path="name">
          <NInput v-model:value="modalForm.name" clearable placeholder="请输入父级商品分类名称" />
        </NFormItem>
        <NFormItem label="封面图" path="cover" style="width:100%">
              <NImage v-if="modalForm.cover" width="60" style="border-radius: 5px;margin-right: 15px;"
                  :src="modalForm.cover"></NImage>
              <NUpload :action="data.uploadAction" :headers="{ token: data.token }" :max="1"
                  :show-file-list=false :custom-request="customRequestMethod" list-type="image">
                  <NButton>上传</NButton>
              </NUpload>
          </NFormItem>
        <NFormItem label="横幅" path="banner" style="width:100%">
              <NImage v-if="modalForm.banner" width="60" style="border-radius: 5px;margin-right: 15px;"
                  :src="modalForm.banner"></NImage>
              <NUpload :action="data.uploadAction" :headers="{ token: data.token }" :max="1"
                  :show-file-list=false :custom-request="customRequestMethod2" list-type="image">
                  <NButton>上传</NButton>
              </NUpload>
          </NFormItem>
        <NFormItem label="备注" path="desc">
          <NInput v-model:value="modalForm.desc" type="textarea" clearable />
        </NFormItem>
        <NFormItem label="排序" path="order">
          <NInputNumber v-model:value="modalForm.order" min="0"></NInputNumber>
        </NFormItem>
        <NFormItem label="描述属性" path="attribute_ms_id">
            <NSelect style="width: 200px;"  v-model:value="modalForm.attribute_ms_id" multiple  :options="attribute_ms_option" placeholder="请输入标签"/>
        </NFormItem>
        <NFormItem label="规格属性" path="attribute_gg_id">
            <NSelect style="width: 200px;"  v-model:value="modalForm.attribute_gg_id" multiple  :options="attribute_gg_option" placeholder="请输入标签"/>
        </NFormItem>
      </NForm>
    </CrudModal>
  </CommonPage>
</template>
